// PC_Comm.c

#include "Temperature_logger.h"


      
void sendChar(char data)
{
    int i = 0; 
    // To send data with the USART put the data in the USART data register
    UDR = data;
    // Check to see if the global interrupts are enabled 
    if(SREG & 0x80) 
            { // Wait until the byte is sent or we count out 
            while ( !(UCSRA&0x40) && (i<10000) ) 
            { 
                  i++; 
            } 
    } else // Wait until the byte is sent 
            while( !(UCSRA&0x40));         
            // Clear the TXCflag 
            UCSRA=UCSRA|0x40;        
}




void sendString(char s[])
{ 
     int i = 0; 
     while(i < 64) // don't get stuck if it is a bad string 
     {
           if( s[i] == '\0' ) break; // quit on string terminator
           sendChar(s[i++]); 
     } 
}





void USARTinit() 
{ 
     // Increase the oscillator to 2 Mhz for the 19200 baudrate: 
     CLKPR = (1<<CLKPCE);   // set Clock Prescaler Change Enable
     // set prescaler = 4, Inter RC 8Mhz / 4 = 2Mhz
     CLKPR = (1<<CLKPS1);

     // Set the USART baudrate registers for 9600
     UBRRH = 0;//(unsigned char)(baudrate>>8); 
     UBRRL = 12;//(unsigned char)baudrate;
     
       
     // Enable receiver and transmitter 
     UCSRB = (1<<RXEN)|(1<<TXEN)|(0<<RXCIE)|(0<<UDRIE);
     
     // Set the USART to asynchronous at 8 bits no parity and 1 stop bit 
     UCSRC = (0<<UMSEL)|(0<<UPM0)|(0<<USBS)|(3<<UCSZ0)|(0<<UCPOL);

        // Enable interrupts
    sei(); 
    
    // Setup the interrupt mask and flags
   PCMSK1 = (1<<PINB6) | (1<<PINB4);       // set pin-change interrupt mask
     EIFR   = (1<<PCIF1);                    // clear external intterupt flag 1
   EIMSK  = (1<<PCIE1);                // enable external interrupt 1   
}

void USARTdisable() 
{ 
      // Disable receiver and transmitter 
UCSRB = (0<<RXEN)|(0<<TXEN);
DDRB |= 0xD8;
PORTB |= PINB_MASK;
DDRE |= 0x00;
PORTE |= PINE_MASK;
PCMSK0 = PINE_MASK;
PCMSK1 = PINB_MASK;
EIFR = (1<<6) | (1<<7);
EIMSK = (1<<6) | (1<<7);
DDRB = 0x00;
PORTB = 0xFF;
PORTB |= (1<<PORTB3) | (1<<PORTB2) | (1<<PORTB1) | (1<<PORTB0);
DDRB |= (1<<PORTB2) | (1<<PORTB1) | (1<<PORTB0);		//Set MOSI, SCK AND SS as outputs
 }

